package com.kgo.eidtor.controller;

import cn.hutool.core.util.IdUtil;
import com.kgo.eidtor.dao.ImageSaveEntityMapper;
import com.kgo.eidtor.entity.ImageSaveEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author keepgoon
 * @Description: TODO
 * @date 2019/3/2120:55
 */
@RestController
@CrossOrigin
public class ImageController {
    private Logger log = LoggerFactory.getLogger(ImageController.class);

    @Resource
    private ImageSaveEntityMapper imageSaveMapper;
    private static final String RootFilePath =  "D:/staticFile/";
    @RequestMapping(value="/image/uploadimg")
    public @ResponseBody
    Map<String,Object> demo(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {

        Map<String,Object> resultMap = new HashMap<String,Object>();
        String realPath = RootFilePath;
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        //保存
        try {
            /*            file.transferTo(targetFile);*/
            byte[] bytes = file.getBytes();
            ImageSaveEntity imageSaveEntity = new ImageSaveEntity();
            imageSaveEntity.setId(IdUtil.simpleUUID());
            imageSaveEntity.setFileName(fileName);
            imageSaveEntity.setImageContent(bytes);
            imageSaveMapper.insert(imageSaveEntity);
            //Path path = Paths.get(RootFilePath + file.getOriginalFilename());
            //Files.write(path, bytes);
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功！");
            resultMap.put("url","http://127.0.0.1:8866/image/download?filename="+imageSaveEntity.getId());
            log.info("上传成功");
        } catch (Exception e) {
            resultMap.put("success", 0);
            resultMap.put("message", "上传失败！");
            log.info("上传失败");
            e.printStackTrace();
        }
        System.out.println(resultMap.get("success"));
        return resultMap;
    }
    @GetMapping(value = "/image/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String fileName) throws IOException {
        String property = RootFilePath;
        log.info("================================================");
        log.info("\nfileName  : " +fileName);
        File file3 = new File(property);
        String filePath = file3.getParent() + File.separator + "upload" + File.separator + fileName;
        log.info(filePath);
        ImageSaveEntity imageSaveEntity = imageSaveMapper.selectByPrimaryKey(fileName);
        @SuppressWarnings("resource")
        InputStream in = new ByteArrayInputStream(imageSaveEntity.getImageContent());// 将该文件加入到输入流之中
        String[] fileN = imageSaveEntity.getFileName().split(".");
        byte[] body = null;
        body = new byte[in.available()];// 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取（或跳过）的估计剩余字节数
        in.read(body);// 读入到输入流里面
        fileName=imageSaveEntity.getId()+fileName.indexOf(fileName.length()-1);
        fileName = new String(fileName.getBytes("gbk"), "iso8859-1");// 防止中文乱码
        HttpHeaders headers = new HttpHeaders();// 设置响应头
        headers.add("Content-Disposition", "attachment;filename=" + fileName);
        HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }





}
